using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.Doctor.Drug;
using B.S.NewMedical.Api.Read.DTOS.Drug;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Doctor.Drug
{
    /// <summary>
    /// 获取药品列表处理器
    /// </summary>
    public class GetDrugsHandler : IRequestHandler<GetDrugsCommand, ApiResult<List<DrugDto>>>
    {
        private readonly IBaseRepository<DrugInfoModel> _drugRepository;
        private readonly IBaseRepository<DrugCategoryModel> _categoryRepository;
        private readonly ILogger<GetDrugsHandler> _logger;
        private readonly IMapper _mapper;

        public GetDrugsHandler(
            IBaseRepository<DrugInfoModel> drugRepository,
            IBaseRepository<DrugCategoryModel> categoryRepository,
            ILogger<GetDrugsHandler> logger,
            IMapper mapper)
        {
            _drugRepository = drugRepository;
            _categoryRepository = categoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<DrugDto>>> Handle(GetDrugsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取药品列表，类别ID：{CategoryId}", request.CategoryId);

                var query = _drugRepository.GetAll().Where(d => !d.IsDeleted);

                // 按类别筛选
                if (request.CategoryId.HasValue)
                {
                    query = query.Where(d => d.CategoryId == request.CategoryId.Value);
                }

                var drugs = await query.ToListAsync(cancellationToken);
                var categories = await _categoryRepository.GetAll().Where(c => !c.IsDeleted).ToListAsync(cancellationToken);

                // 手动映射并添加分类名称
                var result = drugs.Select(d => new DrugDto
                {
                    Id = d.Id,
                    CategoryId = d.CategoryId,
                    CategoryName = categories.FirstOrDefault(c => c.Id == d.CategoryId)?.CategoryName ?? "未知类别",
                    DrugName = d.DrugName,
                    Dosage = d.Dosage,
                    Efficacy = d.Efficacy,
                    Price = d.Price,
                    IsPrescription = d.IsPrescription,
                    LimitQuantity = d.LimitQuantity,
                    ImageUrl = d.ImageUrl
                }).ToList();

                return new ApiResult<List<DrugDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取药品列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取药品列表时发生异常");
                return new ApiResult<List<DrugDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取药品列表失败：" + ex.Message
                };
            }
        }
    }
}